package com.baomidou.springwind.excel;

import com.baomidou.framework.exception.WebException;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * excel文件读取
 *
 * @author luox
 */
public abstract class ExcelReader<T> {

    /**
     * 处理excel内容
     *
     * @param in
     * @param batchId
     * @throws Exception
     */
    public final String handleExcel(InputStream in, Long batchId,String fileName) throws Exception {
        //文件的后缀名
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        try{
            if(".xls".equals(suffix)){
                HSSFWorkbook book=new HSSFWorkbook(in);
                List<T> dataList = verifyData(book);
                saveData(dataList, batchId);
            }else if(".xlsx".equals(suffix)){
                XSSFWorkbook  book=new XSSFWorkbook(in);
                List<T> dataList = verifyData7(book);
                String str1=saveData(dataList, batchId);
                if(str1.length()>1){
                    return str1;
                }
            }else{
                String str0="不支持该文件类型";
                System.out.println(str0);
                return str0;
            }
        }catch (Exception e){
            System.out.println("上传文件出错");
        }
        return "";


    }

    /**
     * 验证数据2003
     */
    protected abstract List<T> verifyData(HSSFWorkbook workbook);

    /**
     * 验证数据2007
     */
    protected abstract List<T> verifyData7(XSSFWorkbook workbook);


    /**
     * 构建数据
     */
    protected abstract String saveData(List<T> dataList, Long batchId);


//
//    /**
//     * 构造出库记录
//     *
//     * @return
//     * @throws Exception
//     */
//    public Others buildOthers() throws Exception {
//        Others others = new Others();
//        others.setBatchId(batchId);
//        HSSFSheet sheet = workbook.getSheetAt(2);
//        int lastRowNum = sheet.getLastRowNum();
//        Field[] fields = Others.class.getDeclaredFields();
//        for (Field f : fields) {
//            if (f.getName().startsWith("c")) {
//                Class type = f.getType();
//                f.setAccessible(true);
//                if (type == BigDecimal.class) {
//                    f.set(others, new BigDecimal(getStringCellValue(sheet.getRow(Integer.valueOf(f.getName().replace("c", ""))), 1)));
//                } else {
//                    f.set(others, getIntCellValue(sheet.getRow(Integer.valueOf(f.getName().replace("c", ""))), 1));
//                }
//            }
//        }
//        for (int i = 1; i < lastRowNum; i++) {
//            sheet.getRow(i);
//        }
//        return others;
//    }
//
//    /**
//     * 构造资源
//     *
//     * @return
//     * @throws Exception
//     */
//    public List<Resource> buildResource() throws Exception {
//        List<Resource> resourceList = new ArrayList<Resource>(ResourceEnum.values().length);
////        ExcelReader reader = new ExcelReader(new File("D:\\demo\\framework\\src\\main\\webapp\\WEB-INF\\static\\template\\file.xls"));
//        for (ResourceEnum resourceEnum : ResourceEnum.values()) {
//            String type = String.valueOf(resourceEnum.getType());
//            if (type.startsWith("1")) {
//                resourceList.add(buildOperator(resourceEnum));
//            } else if (type.startsWith("2")) {
//                resourceList.add(buildEquipment(resourceEnum));
//            } else if (type.startsWith("3")) {
//                resourceList.add(buildWorkSpace(resourceEnum));
//            }
//        }
//        return resourceList;
//    }
//
//    private Resource buildOperator(ResourceEnum resEnum) {
//        Resource resource = new Resource();
//        HSSFSheet sheet = workbook.getSheetAt(0);
//        resource.setBatchId(batchId);
//        resource.setResType(resEnum.getType());
//        String amount = getStringCellValue(sheet.getRow(3), resEnum.getCellIndex());
//        String ability = getStringCellValue(sheet.getRow(4), resEnum.getCellIndex());
//        String locomotivity = getStringCellValue(sheet.getRow(5), resEnum.getCellIndex());
//        String price = getStringCellValue(sheet.getRow(6), resEnum.getCellIndex());
//        if (StringUtils.isNotEmpty(amount)) {
//            resource.setAmount(new BigDecimal(amount));
//        }
//        if (StringUtils.isNotEmpty(ability)) {
//            resource.setAbility(Integer.parseInt(ability));
//        }
//        if (StringUtils.isNotEmpty(locomotivity)) {
//            resource.setLocomotivity(Integer.parseInt(locomotivity));
//        }
//        if (StringUtils.isNotEmpty(price)) {
//            resource.setPrice(new BigDecimal(price));
//        }
//        return resource;
//    }
//
//    private Resource buildEquipment(ResourceEnum resEnum) {
//        Resource resource = new Resource();
//        HSSFSheet sheet = workbook.getSheetAt(0);
//        resource.setResType(resEnum.getType());
//        resource.setBatchId(batchId);
//        String amount = getStringCellValue(sheet.getRow(10), resEnum.getCellIndex());
//        String ability = getStringCellValue(sheet.getRow(11), resEnum.getCellIndex());
//        String locomotivity = getStringCellValue(sheet.getRow(12), resEnum.getCellIndex());
//        String price = getStringCellValue(sheet.getRow(13), resEnum.getCellIndex());
//        if (StringUtils.isNotEmpty(amount)) {
//            resource.setAmount(new BigDecimal(amount));
//        }
//        if (StringUtils.isNotEmpty(ability)) {
//            resource.setAbility(Integer.parseInt(ability));
//        }
//        if (StringUtils.isNotEmpty(locomotivity)) {
//            resource.setLocomotivity(Integer.parseInt(locomotivity));
//        }
//        if (StringUtils.isNotEmpty(price)) {
//            resource.setPrice(new BigDecimal(price));
//        }
//        return resource;
//    }
//
//    private Resource buildWorkSpace(ResourceEnum resEnum) {
//        Resource resource = new Resource();
//        HSSFSheet sheet = workbook.getSheetAt(0);
//        resource.setResType(resEnum.getType());
//        resource.setBatchId(batchId);
//        String amount = getStringCellValue(sheet.getRow(17), resEnum.getCellIndex());
//        String price = getStringCellValue(sheet.getRow(18), resEnum.getCellIndex());
//        if (StringUtils.isNotEmpty(amount)) {
//            resource.setAmount(new BigDecimal(amount));
//        }
//        if (StringUtils.isNotEmpty(price)) {
//            resource.setPrice(new BigDecimal(price));
//        }
//        return resource;
//    }
//
//    public List<NetworkNode> buildNetworkNode() {
//        List<NetworkNode> nodeList = new ArrayList<NetworkNode>();
//        buildFactoryNode(nodeList);
//        buildDistributeCenterNode(nodeList);
//        buildCustomNode(nodeList);
//        return nodeList;
//    }
//
//    private void buildFactoryNode(List<NetworkNode> nodeList) {
//        HSSFSheet sheet = workbook.getSheetAt(0);
//        int lastRowNum = sheet.getLastRowNum();
//        NetworkNode node;
//        for (int i = 1; i <= lastRowNum; i++) {
//            sheet.getRow(i);
//            node = new NetworkNode();
//            node.setBatchId(batchId);
//            node.setNodeType(NodeTypeEnum.FACTORY.type);
//            node.setNodeName(getStringCellValue(sheet.getRow(i), 0));
//            node.setCoordinateX(new BigDecimal(getStringCellValue(sheet.getRow(i), 1)));
//            node.setCoordinateY(new BigDecimal(getStringCellValue(sheet.getRow(i), 2)));
//            nodeList.add(node);
//        }
//    }
//
//    private void buildDistributeCenterNode(List<NetworkNode> nodeList) {
//        HSSFSheet sheet = workbook.getSheetAt(1);
//        int lastRowNum = sheet.getLastRowNum();
//        NetworkNode node;
//        for (int i = 1; i <= lastRowNum; i++) {
//            sheet.getRow(i);
//            node = new NetworkNode();
//            node.setBatchId(batchId);
//            node.setNodeType(NodeTypeEnum.DISTRIBUTE_CENTER.type);
//            node.setNodeName(getStringCellValue(sheet.getRow(i), 0));
//            node.setCoordinateX(new BigDecimal(getStringCellValue(sheet.getRow(i), 1)));
//            node.setCoordinateY(new BigDecimal(getStringCellValue(sheet.getRow(i), 2)));
//            nodeList.add(node);
//        }
//    }
//
//    private void buildCustomNode(List<NetworkNode> nodeList) {
//        HSSFSheet sheet = workbook.getSheetAt(2);
//        int lastRowNum = sheet.getLastRowNum();
//        NetworkNode node;
//        for (int i = 1; i <= lastRowNum; i++) {
//            sheet.getRow(i);
//            node = new NetworkNode();
//            node.setBatchId(batchId);
//            node.setNodeType(NodeTypeEnum.CUSTOM.type);
//            node.setNodeName(getStringCellValue(sheet.getRow(i), 0));
//            node.setCoordinateX(new BigDecimal(getStringCellValue(sheet.getRow(i), 1)));
//            node.setCoordinateY(new BigDecimal(getStringCellValue(sheet.getRow(i), 2)));
//            node.setAmount(new BigDecimal(getStringCellValue(sheet.getRow(i), 3)));
//            nodeList.add(node);
//        }
//    }

    protected String getStringCellValue(HSSFRow row, int cellIndex) {
        HSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }

    protected Date getDateCellValue(HSSFRow row, int cellIndex) {
        HSSFCell cell = row.getCell(cellIndex);
        if (cell == null) {
            return null;
        }
        return cell.getDateCellValue();
    }

    protected int getIntCellValue(HSSFRow row, int cellIndex) {
        HSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        return Double.valueOf(cell.getNumericCellValue()).intValue();
    }



    protected double getdoubleCellValue(HSSFRow row, int cellIndex) {
        HSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        return cell.getNumericCellValue();
    }

    protected String getStringCellValue7(XSSFRow row, int cellIndex) {
        XSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        return cell.getStringCellValue();
    }

    protected Date getDateCellValue7(XSSFRow row, int cellIndex) {
        XSSFCell cell = row.getCell(cellIndex);
        if (cell == null) {
            return null;
        }
        return cell.getDateCellValue();
    }

    protected int getIntCellValue7(XSSFRow row, int cellIndex) {
        XSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        return Double.valueOf(cell.getNumericCellValue()).intValue();
    }



    protected double getdoubleCellValue7(XSSFRow row, int cellIndex) {
        XSSFCell cell = row.getCell(cellIndex);
        cell.setCellType(Cell.CELL_TYPE_NUMERIC);
        return cell.getNumericCellValue();
    }

    protected Long getCurrentUserId() {
        return this.getSSOToken().getId();
    }

    protected SSOToken getSSOToken() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        SSOToken tk = SSOHelper.attrToken(request);
        if (tk == null) {
            throw new WebException("-1", "The user does not exist, please relogin.");
        } else {
            return tk;
        }
    }
}
